package org.obm.mina;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.util.zip.GZIPInputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ByteUtil {

	private static final Logger logger = LoggerFactory
			.getLogger(ByteUtil.class);

	public static void closeStream(InputStream is) {
		if (is == null)
			return;

		if (is instanceof PipedInputStream) {
			try {
				while (is.read() != -1) {
				}
			} catch (Exception e) {
				logger
						.debug(
								"ignoring exception while draining PipedInputStream",
								e);
			}
		}

		try {
			is.close();
		} catch (Exception e) {
			logger.debug("ignoring exception while closing input stream", e);
		}
	}

	public static void closeStream(OutputStream os) {
		if (os == null)
			return;

		try {
			os.close();
		} catch (Exception e) {
			logger.debug("ignoring exception while closing output stream", e);
		}
	}

	/**
	 * Determines if the data in the given stream is gzipped. Requires that the
	 * <tt>InputStream</tt> supports mark/reset.
	 */
	public static boolean isGzipped(InputStream in) throws IOException {
		in.mark(2);
		int header = in.read() | (in.read() << 8);
		in.reset();
		if (header == GZIPInputStream.GZIP_MAGIC) {
			return true;
		}
		return false;
	}
}
